<script lang="ts" setup>
import type { FileInfo } from '@/index.d';
import { deleteFileInfo, getFileInfoByKeyWord, useLoginUserStore } from '@/index';
import {
  type UploadFile,
  type UploadFiles,
  type UploadInstance,
  type UploadProgressEvent,
  type UploadRawFile
} from 'element-plus';

const props = defineProps({
  keyWord: {
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: true
  }
});

const upload = ref<UploadInstance>();
const { loginUser } = useLoginUserStore();
const headers = { Authorization: loginUser.token };
const extraData: FileInfo = {
  keyWord: props.keyWord
};
const imageUrl = ref<string>();
const loading = ref<boolean>(false);
const handleBeforeUpload = (rawFile: UploadRawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage({
      type: 'error',
      message: '请选择jpg格式的文件。'
    });
    return false;
  } else if (rawFile.size > 2 * 1024 * 1024) {
    ElMessage({
      type: 'error',
      message: '请选择小于2M的图片。'
    });
    return false;
  } else {
    extraData.creatorId = loginUser.id;
    extraData.updaterId = loginUser.id;
    extraData.name = rawFile.name;
    extraData.size = rawFile.size;
    extraData.uid = rawFile.uid;
    extraData.type = rawFile.type;
    return true;
  }
};

const handleProgress = (
  evt: UploadProgressEvent,
  uploadFile: UploadFile,
  uploadFiles: UploadFiles
) => {
  loading.value = true;
};

const handleSuccess = (response: FileInfo, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  loading.value = false;
  ElMessage({
    type: 'success',
    message: '文件上传成功。'
  });
};

const handlePreview = (uploadFile: UploadFile) => {
  window.open(uploadFile.url, '_blank');
};

const handleRemove = async (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  deleteFileInfo('physicalDeleteByUid', uploadFile.uid);
};

const handleError = (error: Error, uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  console.log(error);
  console.log(uploadFile);
  console.log(uploadFiles);
};

const initFileList = async () => {
  const res = await getFileInfoByKeyWord(props.keyWord);
  if (res) {
    imageUrl.value = res.url;
  }
};

onMounted(async () => {
  initFileList();
});
</script>
<template>
  <el-upload
    ref="upload"
    class="avatar-uploader"
    action="/api/base/file/fileInfo/uploadOne"
    accept=".jpg"
    :data="extraData"
    :headers="headers"
    :disabled="props.disabled"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-success="handleSuccess"
    :on-error="handleError"
    :on-progress="handleProgress"
    :before-upload="handleBeforeUpload"
    :show-file-list="false"
    v-loading="loading"
    v-bind="$attrs"
  >
    <template #default>
      <el-avatar v-if="imageUrl" shape="square" :size="178" :src="imageUrl" alt="图片加载中" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /> </el-icon>
    </template>
  </el-upload>
</template>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
